package com.xoa.service.cms.core;

import com.xoa.model.cms.CmsChannelInfo;
import com.xoa.model.cms.CmsSiteInfo;
import com.xoa.model.cms.SiteTemplateModel;
import com.xoa.service.cms.CmsChannelService;
import com.xoa.service.cms.CmsDocumentService;
import com.xoa.service.cms.CmsSiteService;
import com.xoa.service.cms.CmsSiteTemplateService;
import com.xoa.service.enclosure.EnclosureService;
import freemarker.core.Environment;
import freemarker.template.*;

import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * @author 程叶同
 * @date 2018/8/13 14:42
 * @desc  模板栏目Document标签解析
 */
public class CmsDocumentDirective implements TemplateDirectiveModel {

	@Override
	public void execute(Environment env, Map params, TemplateModel[] loopVars,
                        TemplateDirectiveBody body) throws TemplateException, IOException {
		// TODO Auto-generated method stub
		int chnlDocId = FileUtils.getInteger(params.get("chnlDocId"),0);//指定chnlDocId
		int siteId = FileUtils.getInteger(env.getCustomAttribute("SITE_ID"),0);
		int context_chnlDocId = FileUtils.getInteger(env.getCustomAttribute("CHNLDOC_ID"),0);
		
		Writer writer = env.getOut();
		boolean preview = (Boolean) env.getCustomAttribute("preview");
		
		CmsDocumentService documentService = (CmsDocumentService) env.getCustomAttribute("documentService");
		CmsChannelService channelService = (CmsChannelService) env.getCustomAttribute("channelService");
		CmsSiteService siteService = (CmsSiteService) env.getCustomAttribute("siteService");
		CmsSiteTemplateService siteTemplateService = (CmsSiteTemplateService) env.getCustomAttribute("siteTemplateService");
		
		EnclosureService attachmentService = (EnclosureService)env.getCustomAttribute("attachmentService");
		
		Object loopObj = env.getCustomAttribute("loopObj");//上层循环变量
		TemplateModel this0 = env.getVariable("this");
		Map data = null;
		try {
		if(chnlDocId!=0){
				data = documentService.getDocumentByChnlDocId(chnlDocId);

		}else{
			data = documentService.getDocumentByChnlDocId(context_chnlDocId);
		}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		if(data==null){
			return;
		}
		env.setCustomAttribute("docId", data.get("docId"));
		
		
		CmsChannelInfo channelInfo = channelService.getChannelInfo(FileUtils.getInteger(data.get("chnlId"), 0));
		SiteTemplateModel st = siteTemplateService.getSiteTemplate(channelInfo.getDetailTpl());
		CmsSiteInfo siteInfo = siteService.getSiteInfo(siteId);
		
		
		String absPath = channelService.getChannelAbsolutePath(channelInfo.getSid());
		
		if(st!=null){
			data.put("ABS_PATH", absPath+"/"+data.get("chnlDocId")+"."+siteInfo.getPubFileExt());//绝对路径
			int index = absPath.indexOf("/", 2);
			absPath = absPath.substring(index+1);
			data.put("REL_PATH", env.getCustomAttribute("ROOT_PATH")+absPath+"/"+data.get("chnlDocId")+"."+siteInfo.getPubFileExt());//相对路径
		}
		
		//处理日期
		data.put("writeTimeDesc", FileUtils.format((Date)data.get("writeTime")));
		data.put("crTimeDesc", FileUtils.format((Date)data.get("crTime")));
		
		
		if(!preview){
			//处理内容中的图片
			String htmlContent = (String)data.get("htmlContent");
			List oldUrls = new ArrayList();
			List newUrls = new ArrayList();
			String reg = "<img[^<>]*?\\ssrc=['\"]?(.*?)['\"].*?>";
			Pattern p= Pattern.compile(reg);
			Matcher m=p.matcher(htmlContent);
			String channelPath = channelService.getChannelRootPath(channelInfo.getSid());

			htmlContent = FileUtils.replaceImageUrl(oldUrls, htmlContent, newUrls);
			
			//处理视频，音频文件
			List oldUrls2 = new ArrayList();
			List newUrls2 = new ArrayList();
			String reg2 = "<embed[^<>]*?\\ssrc=['\"]?(.*?)['\"].*?>";
			Pattern p2= Pattern.compile(reg2);
			Matcher m2=p2.matcher(htmlContent);
			htmlContent = FileUtils.replaceImageUrl(oldUrls2, htmlContent, newUrls2);
			data.put("htmlContent", htmlContent);
		}
		//如果是预览中
		if(preview){
			data.put("ABS_PATH", "/cmsPub/portal?siteId="+siteId+"&channelId="+data.get("chnlId0")+"&chnlDocId="+chnlDocId);//绝对路径
			data.put("REL_PATH", "/cmsPub/portal?siteId="+siteId+"&channelId="+data.get("chnlId0")+"&chnlDocId="+chnlDocId);//相对路径
		}
		
		Map _this = new HashMap();
		_this.put("instance", data);
		env.setVariable("this", new DefaultObjectWrapper().wrap(_this));
		env.setCustomAttribute("loopObj", data);
		
		if(body!=null){
			body.render(writer);
		}
		env.setVariable("this", this0);
		env.setCustomAttribute("loopObj", loopObj);
	}

}
